package com.lw.config.util;

/**
 * @Author LW
 * @2022/5/6 11:45
 */

import lombok.extern.slf4j.Slf4j;
import org.drools.core.impl.InternalKnowledgeBase;
import org.kie.api.KieBase;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.internal.utils.KieHelper;

/**
 * Drools规则引擎工具类
 * @author yuantao
 * @date 2021/12/8
 */
@Slf4j
public class DroolsUtil {

    /**
     * 编译规则
     * @param kieBase
     * @param ruleName
     * @param definition
     */
    public static boolean buildRule(KieBase kieBase, String ruleName, String definition) {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(definition, ResourceType.DRL);

        // 处理编译错误
        Results results = kieHelper.verify();
        if( results.hasMessages( Message.Level.ERROR ) ){
            log.error("编译规则{}出错：{}", ruleName, results.getMessages() );

            return false;
        } else {
            ((InternalKnowledgeBase)kieBase).addPackages(kieHelper.build().getKiePackages());

            return true;
        }
    }

    /**
     * 验证规则语法
     * @param definition
     * @return
     */
    public static boolean verifyRule(String definition) {
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(definition, ResourceType.DRL);
        Results results = kieHelper.verify();

        // 出现编译错误则返回false
        if(results.hasMessages( Message.Level.ERROR ) ){
            return false;
        }
        return true;
    }

    /**
     * 从规则引擎中删除规则
     * @param kieBase
     * @param rulePackage
     * @param ruleName
     */
    public static void removeRule(KieBase kieBase, String rulePackage, String ruleName) {
        kieBase.removeRule(rulePackage, ruleName);
    }
}

